package cn.tiancaifan.micro.utils;


import cn.tiancaifan.micro.entity.ConstantProperties;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AliyunOSSUtil {
    @Autowired
    private ConstantProperties constantProperties;

    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 上传
     * @param key,input
     * @return
     */
    public String upload(String key, InputStream input){
        System.out.println("=========>OSS文件上传开始："+key);
        String endpoint= constantProperties.getEndpoint();
        String accessKeyId= constantProperties.getKeyid();
        String accessKeySecret=constantProperties.getKeysecret();
        String bucketName=constantProperties.getBucketname();
        String fileHost=constantProperties.getFilehost();
        System.out.println(endpoint+"endpoint");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在，就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl = fileHost+key;
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, input));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                System.out.println("==========>OSS文件上传成功,OSS地址："+fileUrl);
                return fileUrl;
            }
        }catch (OSSException oe){
            oe.printStackTrace();
        }catch (ClientException ce){
            ce.printStackTrace();
        }finally {
            ossClient.shutdown();
        }
        return null;
    }

    /**
     * 删除
     * @param fileKey
     * @return
     */
    public  String deleteBlog(String fileKey){
        System.out.println("=========>OSS文件删除开始");
        String endpoint= constantProperties.getEndpoint();
        String accessKeyId= constantProperties.getKeyid();
        String accessKeySecret=constantProperties.getKeysecret();
        String bucketName=constantProperties.getBucketname();
        String fileHost=constantProperties.getFilehost();
        try {
            OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
            if(!ossClient.doesBucketExist(bucketName)){
                System.out.println("==============>您的Bucket不存在");
                return "您的Bucket不存在";
            }else {
                System.out.println("==============>开始删除Object");
                ossClient.deleteObject(bucketName,fileKey);
                System.out.println("==============>Object删除成功："+fileKey);
                return "==============>Object删除成功："+fileKey;
            }
        }catch (Exception ex){
            System.out.println("删除Object失败:"+ex);
            return "删除Object失败";
        }
    }

    public InputStream exportOssFile( String objectName) throws IOException {
        String endpoint= constantProperties.getEndpoint();
        String accessKeyId= constantProperties.getKeyid();
        String accessKeySecret=constantProperties.getKeysecret();
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        OSSObject ossObject = ossClient.getObject(constantProperties.getBucketname(), objectName);
        return ossObject.getObjectContent();
    }


    /**
     * 查询文件名列表
     * @param bucketName
     * @return
     */
    public List<OSSObjectSummary> getObjectList(String key , String bucketName){
        List<OSSObjectSummary> listRe = new ArrayList<>();
        String endpoint= constantProperties.getEndpoint();
        String accessKeyId= constantProperties.getKeyid();
        String accessKeySecret=constantProperties.getKeysecret();
        try {
            System.out.println("===========>查询文件名列表");
            OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            listObjectsRequest.setPrefix(key);
            ObjectListing list = ossClient.listObjects(listObjectsRequest);
            for(OSSObjectSummary objectSummary : list.getObjectSummaries()){
                System.out.println(objectSummary.getKey());
                listRe.add(objectSummary);
            }
            return listRe;
        }catch (Exception ex){
            System.out.println("==========>查询列表失败:"+ex);
            return new ArrayList<>();
        }
    }

}